package com.aistar.controller;

import com.aistar.pojo.Program;
import com.aistar.pojo.ProgramCollect;
import com.aistar.pojo.ProgramComment;
import com.aistar.pojo.ProgramRecord;
import com.aistar.pojoVO.JudgeResult;
import com.aistar.pojoVO.JudgeTask;
import com.aistar.service.ProgramCollectService;
import com.aistar.service.ProgramCommentService;
import com.aistar.service.ProgramRecordService;
import com.aistar.service.ProgramService;
import com.aistar.serviceVO.ProgramCommentVOService;
import com.aistar.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/program")
public class ProgramController {
    private final ProgramService programService;
    private final ProgramRecordService programRecordService;
    private final ProgramCollectService programCollectService;
    private final ProgramCommentVOService programCommentVOService;
    private final ProgramCommentService programCommentService;

    @Autowired
    public ProgramController(ProgramService programService,
                             ProgramRecordService programRecordService,
                             ProgramCollectService programCollectService,
                             ProgramCommentVOService programCommentVOService,
                             ProgramCommentService programCommentService) {
        this.programService = programService;
        this.programRecordService = programRecordService;
        this.programCollectService = programCollectService;
        this.programCommentVOService = programCommentVOService;
        this.programCommentService = programCommentService;
    }

    @RequestMapping
    public ModelAndView getByPageForIndex(Integer page, String kw) {
        page = page == null ? 1 : page;
        ModelAndView mav = new ModelAndView();
        if(kw == null || kw.equals(""))
            kw = null;
        else
            mav.addObject("kw", kw);
        ServerResponse kwSS = programService.getByKeywords(page, 10, kw);
        if(MessageUtil.STATUS_SUCCESS.equals(kwSS.getStatus()))
            mav.addObject("pageInfo", kwSS.getData());
        ServerResponse hot = programService.getHot(10);
        if(MessageUtil.STATUS_SUCCESS.equals(hot.getStatus()))
            mav.addObject("hot", hot.getData());
        mav.setViewName("program/programHome");
        return mav;
    }

    //前往练习页
    @RequestMapping("/goProgram/{programId}")
    public String getProgram(@PathVariable("programId") Integer programId, HttpServletRequest request) {
        Program program = (Program) programService.getById(programId).getData();
        List<Program> programs = (List<Program>) programService.getAll().getData();
        int programSize = programs.size();
        request.setAttribute("program", program);
        request.setAttribute("programSize", programSize);
        return "program/programDo";
    }

    //提交代码
    @RequestMapping("/submitProgram/{customerId}/{programId}")
    @ResponseBody
    public ServerResponse serverResponse(@PathVariable("programId") Integer programId, @PathVariable("customerId") Integer customerId, @RequestBody JudgeTask judgeTask) {
        JudgeResult judgeResult = JudgeUtil.doPost(judgeTask);
        ProgramRecord programRecord = new ProgramRecord();
        programRecord.setCustomerId(customerId);
        programRecord.setProgramId(programId);
        programRecord.setProgramStartTime(new Date());//做题开始时间即提交时间
        programRecord.setProgramRecordLanguage(judgeTask.getJudgeId().toString());//语言类型
        /*if (judgeResult.getGlobalMsg() != null) {*/
            programRecord.setProgramRecordResult(judgeResult.getResult().get(0).getStatus());
            programRecord.setProgramRecordPassCode(judgeTask.getSrc());//最近一次通过代码
            programRecord.setProgramRecordExecuteTime(judgeResult.getResult().get(0).getTimeUsed().intValue());//执行用时
            programRecord.setProgramRecordMemory(judgeResult.getResult().get(0).getMemoryUsed().intValue());//内存消耗
       /* }*/

        return programRecordService.add(programRecord);
    }

    //收藏
    @RequestMapping("/collect/{customerId}/{programId}")
    @ResponseBody
    public ServerResponse collect(@PathVariable("customerId") Integer customerId, @PathVariable("programId") Integer programId) {
        String field = customerId + RedisMessage.SEPARATOR + programId;
        String value = (String) RedisUtil.hget(RedisMessage.PROGRAM_COLLECT_KEY, field);
        int valueType;
        if (value == null) {
            ServerResponse serverResponse = programCollectService.getByProgramIdAndCustomerId(programId, customerId);
            if (MessageUtil.STATUS_SUCCESS.equals(serverResponse.getStatus()))
                valueType = ((ProgramCollect) serverResponse.getData()).getStatus() == 0 ? 1 : 0;
            else
                valueType = 1;
        } else
            valueType = value.split(RedisMessage.SEPARATOR)[0].equals("0") ? 1 : 0;
        value = valueType + RedisMessage.SEPARATOR + new Date().getTime();
        if (RedisUtil.hset(RedisMessage.PROGRAM_COLLECT_KEY, field, value))
            return ServerResponse.modifySuccess(valueType == 1 ? 1 : -1);
        return ServerResponse.modifyFailed();
    }

    //初始话点赞状态
    @RequestMapping("/isCollect/{customerId}/{programId}")
    @ResponseBody
    public ServerResponse isCollect(@PathVariable("customerId") Integer customerId, @PathVariable("programId") Integer programId) {
        Object object = programCollectService.getByProgramIdAndCustomerId(programId, customerId).getData();
        if (object != "查询失败") {
            ProgramCollect programCollect = (ProgramCollect) object;
            return ServerResponse.getSuccess(programCollect);
        }
        return ServerResponse.getFailed();
    }

    //前往查看答案
    @RequestMapping("/goComment/{programId}")
    public String goComment(@PathVariable("programId") Integer programId, HttpServletRequest request) {
        request.setAttribute("programId", programId);
        ServerResponse serverResponse = programService.getById(programId);
        if (!MessageUtil.STATUS_FAIL.equals(serverResponse.getStatus()))
            request.getSession().setAttribute("program", serverResponse.getData());
        ServerResponse sr = programCommentVOService.getByProgramId(programId);
        if (!MessageUtil.STATUS_FAIL.equals(sr.getStatus()))
            request.setAttribute("commentList", sr.getData());
        return "program/programComment";
    }

    @PostMapping("/comment/add")
    @ResponseBody
    public ServerResponse add(@RequestBody ProgramComment programComment) {
        return programCommentService.add(programComment);
    }
}